<template>
  <div class="container">
    <div class="userInfo">
      <div class="userAvatar">
        <el-avatar :size="100" :rules="rules" :src="userInfo.avatar" @error="true">
          <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
        </el-avatar>
        <!-- <el-upload class="upload" :data="filePath" :action="'/file/upload/picture'" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <el-button plain round type="primary">更换头像</el-button>
        </el-upload> -->
      </div>
      <el-form :model="userInfo" status-icon ref="userInfo" label-width="100px" size="medium" label-position="left">
        <el-row>
          <el-col :span="16">
            <el-form-item label="用户名:" prop="username">
              <el-input v-model="userInfo.username" placeholder="填写用户名"></el-input>
            </el-form-item>
            <el-form-item label="手机号:">
              <span class="mobile">{{userInfo.mobile?userInfo.mobile:'无'}}</span>
              <template v-if="userInfo.mobile">
                <i class="el-ali-check" style="color:#00CD66"><span>已验证</span></i>
              </template>
            </el-form-item>
            <el-form-item label="邮箱:" prop="email">
              <span class="mobile">{{userInfo.email?userInfo.email:'无'}}</span>
              <el-button size="mini" type="primary" round style="margin-left:10px" @click="updateEmail">{{ userInfo.email?'更换邮箱':'绑定邮箱' }}</el-button>
              <el-button v-if="userInfo.email" size="mini" type="danger" round style="margin-left:10px" @click="unbindEmail">取消绑定</el-button>
            </el-form-item>
            <el-form-item label="性别:" prop="sex">
              <el-radio v-model="userInfo.sex" label="1">男</el-radio>
              <el-radio v-model="userInfo.sex" label="2">女</el-radio>
            </el-form-item>
            <el-form-item label="生日:" prop="birthday">
              <el-date-picker v-model="userInfo.birthday" type="date" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="个人简介:" prop="description">
              <el-input v-model="userInfo.description" type="textarea" :rows="4" placeholder="填写你的个人简介"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="save">保存</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-dialog title="绑定邮箱" :visible.sync="dialogVisible" width="40%" :close-on-click-modal="false" @close="resetForm">
        <el-form ref="emailForm" :model="emailForm" label-width="80px" :rules="rules">
          <el-form-item label="新邮箱" prop="email">
            <el-input v-model="emailForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-row>
              <el-col :span="12">
                <el-input v-model="emailForm.code" placeholder="请输入验证码"></el-input>
              </el-col>
              <el-col :span="10" :offset="2">
                <el-button size="small" type="primary" round @click="getCheckCode" :disabled="btnDisabled">{{content}}</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetForm">取 消</el-button>
          <el-button type="primary" @click="bindEmail">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getPersonalInfo, savePersonalInfo, bindEmail } from '@/api/user'
import { getEmailCheckCode } from '@/api/verification'

export default {
  data() {
    return {
      imageUrl: '',
      userInfo: {
        avatar: "",
        username: "",
        mobile: "",
        email: "",
        sex: "",
        birthday: "",
        description: ""
      },
      emailForm: {
        email: '',
        code: ''
      },
      rules: {
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      },
      filePath: {
        childFile: "avatar"
      },
      dialogVisible: false,
      content: "获取验证码",
      btnDisabled: false
    };
  },
  mounted() {
    this.getPersonalInfo()
  },
  methods: {
    getPersonalInfo() {
      getPersonalInfo(this.$store.state.userId).then(res => {
        if (res.flag) {
          this.userInfo = res.data
        }
      })
    },
    save() {
      savePersonalInfo(this.userInfo).then(res => {
        if (res.flag) {
          this.$notify.success('修改成功')
        } else if (res.code == 20008) {
          this.$message.error('用户名已存在')
        }
        this.getPersonalInfo()
      })
    },
    updateEmail() {
      this.dialogVisible = true
    },
    bindEmail() {
      this.$refs['emailForm'].validate((valid) => {
        if (valid) {
          bindEmail(this.emailForm.code, { email: this.emailForm.email }).then(res => {
            if (res.flag) {
              this.$notify.success('邮箱绑定成功')
              this.getPersonalInfo()
              this.resetForm()
            }
          })
        }
      });
    },
    unbindEmail() {
      this.$confirm('确定取消绑定邮箱?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        savePersonalInfo({ id: this.userInfo.id, username: this.userInfo.username, email: "" }).then(res => {
          if (res.flag) {
            this.getPersonalInfo()
            this.$message.success('取消绑定成功');
          }
        })
      }).catch(() => {
        this.$message.info('已取消绑定');
      });
    },
    getCheckCode() {
      if (!this.emailForm.email) return
      getEmailCheckCode({ email: this.emailForm.email }).then(res => {
        if (res.flag) {
          this.$message.success('验证码已发送')
          this.countdown()
        }
      })
    },
    countdown() {
      // 控制倒计时及按钮是否可以点击
      const TIME_COUNT = 60
      this.count = TIME_COUNT
      this.timer = window.setInterval(() => {
        if (this.count > 0 && this.count <= TIME_COUNT) {
          // 倒计时时不可点击
          this.btnDisabled = true
          // 计时秒数
          this.count--
          // 更新按钮的文字内容
          this.content = this.count + 's后重新获取'
        } else {
          // 倒计时完，可点击
          this.btnDisabled = false
          // 更新按钮文字内容
          this.content = '获取验证码'
          // 清空定时器!!!
          clearInterval(this.timer)
          this.timer = null
        }
      }, 1000)
    },
    resetForm() {
      this.dialogVisible = false
      this.$refs['emailForm'].resetFields();
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess(res, file) {
      if (res.flag) {
        this.axios.put("/user/" + this.userId, {
          avatar: res.data.serverPath
        })
          .then(res2 => {
            if (res2.flag) {
              this.$message({
                message: "头像修改成功",
                type: "success"
              })
              this.loadData()
            } else {
              this.$message.error("上传失败")
            }
          })
      } else {
        this.$message.error("上传失败")
      }
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  padding: 100px 5%;
}

@media screen and (max-width: 800px) {
  .userInfo {
    width: 100%;
    margin: 0 auto;
  }
}

@media screen and (min-width: 800px) and (max-width: 1000px) {
  .userInfo {
    width: 80%;
    margin: 0 auto;
  }
}

@media screen and (min-width: 1000px) {
  .userInfo {
    width: 60%;
    margin: 0 auto;
  }
}

.userAvatar button {
  margin-left: 50px;
  position: relative;
  bottom: 40px;
}
.el-form-item {
  line-height: 36px;
  font-size: 17px;
  color: #969696;
  font-weight: 600;
}
.el-ali-check {
  padding: 0 10px;
  font-size: 12px;
  color: #969696;
  font-weight: 400;
}
.el-form-item__content > span {
  font-weight: 400;
}
.mobile {
  font-weight: 400;
  color: #333;
}
.upload {
  display: inline-block;
}
</style>